package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.*;
import com.tanhua.model.vo.*;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Create by: wanglei
 * @Date: 2021/11/7 12:43
 */
//灵魂测试
@Service
public class TestSoulService {

    @DubboReference
    private SoulApi soulApi;
    @DubboReference
    private QuestionSoulApi questionSoulApi;
    @DubboReference
    private OptionApi optionApi;
    @DubboReference
    private UserAndSoulApi userAndSoulApi;
    @DubboReference
    private ReportApi reportApi;
    @DubboReference
    private UserInfoApi userInfoApi;


    //查看试卷列表
    public List<SoulVo> showSouls() {
        Long userId = UserHolder.getUserId();
        List<SoulVo> soulVos = new ArrayList<>();
        List<Soul> souls = soulApi.selectAll();
        for (Soul soul : souls) {
            List<QuestionVo> questionVos = new ArrayList<>();
            String soulIdStr = soul.getId().toHexString();
            List<Question> questions = questionSoulApi.findBySoulId(soulIdStr);
            for (Question question : questions) {
                List<Option> options = optionApi.findByQuestionId(question.getId().toHexString());
                ArrayList<OptionVo> optionVos = new ArrayList<>();
                QuestionVo questionVo = QuestionVo.init(question, optionVos);
                questionVos.add(questionVo);
                for (Option option : options) {
                    OptionVo optionVo = OptionVo.init(option);
                    optionVos.add(optionVo);
                }
            }
            SoulVo soulVo = SoulVo.init(soul, questionVos);
            //根据用户id，查询user_soul表，判断这套试卷的状态。
            if (soul.getId().toHexString().equals("618782fbccb489658208f6b2")){
                //第一套题，直接解锁状态。
                soulVo.setIsLock(0);
                UserAndSoul userAndSoul = userAndSoulApi.findByUserIdAndSoulId(userId, String.valueOf(soul.getId()));
                if ( userAndSoul != null && !StringUtils.isEmpty(userAndSoul.getReportId())){
                    soulVo.setReportId(userAndSoul.getReportId());
                }
                soulVos.add(soulVo);
            }else if (soul.getId().toHexString().equals("6187eb0f775e00002c000585")){
                //第二套题，根据第一套题的reportId是否在user_soul表中存在，来决定是否解锁第二套
                UserAndSoul userAndSoul = userAndSoulApi.findByUserIdAndSoulId(userId, "618782fbccb489658208f6b2");
                if (userAndSoul == null){
                    soulVo.setIsLock(1);
                    soulVos.add(soulVo);
                }else{
                    soulVo.setIsLock(0);
                    UserAndSoul userAndSoul2 = userAndSoulApi.findByUserIdAndSoulId(userId, "6187eb0f775e00002c000585");
                    if (userAndSoul2 != null && !StringUtils.isEmpty(userAndSoul.getReportId())){
                        soulVo.setReportId(userAndSoul2.getReportId());
                    }
                    soulVos.add(soulVo);
                }
            }else{
                //第三套题，判断第二套题的reportId是否在user_soul表中存在，来决定是否解锁第三套
                UserAndSoul userAndSoul = userAndSoulApi.findByUserIdAndSoulId(userId, "6187eb0f775e00002c000585");
                if (userAndSoul == null){
                    soulVo.setIsLock(1);
                    soulVos.add(soulVo);
                }else{
                    soulVo.setIsLock(0);
                    UserAndSoul userAndSoul3 = userAndSoulApi.findByUserIdAndSoulId(userId, "61893a3a6e7c000098005f4c");
                    if (userAndSoul3 != null && !StringUtils.isEmpty(userAndSoul.getReportId())){
                        soulVo.setReportId(userAndSoul3.getReportId());
                    }
                    soulVos.add(soulVo);
                }
            }
        }
        return soulVos;


       /* SoulVo soulVo = new SoulVo();
        soulVo.setIsLock(0);
        //soulVo.setReportId("101");
        List<QuestionVo> questionVos = new ArrayList<>();
        OptionVo optionVo = new OptionVo("1", "A:这是A选项");
        List<OptionVo> optionVos = new ArrayList<>();
        optionVos.add(optionVo);
        QuestionVo questionVo = new QuestionVo("1", "今晚吃啥", optionVos);
        questionVos.add(questionVo);
        soulVo.setQuestions(questionVos);
        soulVo.setCover("http://192.168.136.160:8888/group1/M00/00/00/wKiIoGGH7hCAAxD0AAROPfzDdgE243.jpg");
        soulVo.setLevel("3");
        soulVo.setName("初级测试题");
        soulVo.setId("1");
        soulVo.setStar(3);
        soulVos.add(soulVo);*/
    }

    //提交问卷
    public String submit(Map<String, List<Map<String, String>>> answers) {
        //获取用户id
        Long userId = UserHolder.getUserId();
        //题目的总得分
        Integer score = 0;
        //获取这套卷子，中的一道题的id，从而可以获取这套卷子的id
        ObjectId questionId = null;
        //获取选项id和题目id,根据选项id，查看选项的分数，并进行相加
        List<Map<String, String>> answers1 = answers.get("answers");
        for (Map<String, String> map : answers1) {
            questionId = new ObjectId(map.get("questionId"));
            ObjectId optionId = new ObjectId(map.get("optionId"));
            Option option = optionApi.findById(optionId);
            score += option.getScore();
        }

        //根据分数，获取该用户的测试结果
        String reportId ;
        if (score >= 10 && score <= 20) {
            reportId = "1";    //狐狸型。
        }else if (score >= 21 && score <= 40){
            reportId = "2";   //狮子型
        }else {
            reportId = "3";   //白兔型
        }

        //根据questionId获取，soulId
        Question question = questionSoulApi.findById(questionId);
        String soulId = question.getSoulId();
        //根据userid和soulId查看是否用户已经存在表中

        UserAndSoul userAndSoul = userAndSoulApi.findByUserIdAndSoulId(userId, soulId);
        if (userAndSoul == null){
            userAndSoul = new UserAndSoul();
            //为空，添加数据
            userAndSoul.setUserId(userId);
            userAndSoul.setSoulId(soulId);
            userAndSoul.setIsLock(0);      //是否锁住（0解锁，1锁住）
            userAndSoul.setReportId(reportId);
            userAndSoulApi.save(userAndSoul);
        }else{
            //存在的话，直接更新
            userAndSoulApi.updateByUserIdAndSoulId(userId,soulId);
        }
        return reportId;
    }

    //展示灵魂测试的结果
    public ReportVo showReport(Integer reporetId) {
        ReportVo reportVo = new ReportVo();
        //根据reporetId，查找Report
        Report report = reportApi.findByReportId(reporetId);
        List<DimensionVo> dimensionVos = DimensionVo.getdimensionvos();
        //根据reportId查询，相似测试结果的人
        List<UserAndSoul> userAndSouls = userAndSoulApi.findByReportId(reporetId);
        //获取用户ids
        List<Long> userIds = CollUtil.getFieldValues(userAndSouls, "userId", Long.class);
        List<SimilarYouVo> similarYouVos = new ArrayList<>();
        for (Long userId : userIds) {
            UserInfo userInfo = userInfoApi.findById(userId);
            String avatar = userInfo.getAvatar();
            SimilarYouVo similarYouVo = new SimilarYouVo();
            similarYouVo.setId(Integer.valueOf(String.valueOf(userId)));
            similarYouVo.setAvatar(avatar);
            similarYouVos.add(similarYouVo);
        }

        //组装并返回Vo
        reportVo.setConclusion(report.getConclusion());
        reportVo.setCover(report.getCover());
        reportVo.setDimensions(dimensionVos);
        reportVo.setSimilarYou(similarYouVos);

        return reportVo;
    }
}
